﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.ComponentModel.DataAnnotations;

namespace GestionTaxesRiaApp.Helpers
{
    public class ValidationHelper
    {
        public static void ValidateProperty(string propertyName, object instance, object value)
        {
            ValidationContext context = new ValidationContext(instance, null, null);
            context.MemberName = propertyName;
            Validator.ValidateProperty(value, context);
        }

        public static void SetControlError(Control control, string errorMessage)
        {
            ControlValidationHelper validationHelper =
                new ControlValidationHelper(errorMessage);

            control.SetBinding(Control.TagProperty, new Binding("ValidationError")
            {
                Mode = BindingMode.TwoWay,
                NotifyOnValidationError = true,
                ValidatesOnExceptions = true,
                UpdateSourceTrigger = UpdateSourceTrigger.Explicit,
                Source = validationHelper
            });

            // this line throws a ValidationException with your custom error message;
            // the control will catch this exception and switch to its "invalid" state
            control.GetBindingExpression(Control.TagProperty).UpdateSource();
        }

        public static void ClearControlError(Control control)
        {
            BindingExpression b = control.GetBindingExpression(Control.TagProperty);

            if (b != null)
            {
                ((ControlValidationHelper)b.DataItem).ThrowValidationError = false;
                b.UpdateSource();
            }
        }  
    }

    public class ControlValidationHelper
    {
        private string _message;

        public ControlValidationHelper(string message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            _message = message;
            ThrowValidationError = true;
        }

        public bool ThrowValidationError
        {
            get;
            set;
        }

        public object ValidationError
        {
            get { return null; }
            set
            {
                if (ThrowValidationError)
                {
                    throw new ValidationException(_message);
                }
            }
        }
    } 
}
